const { login, getVoterStatus } = require('../controller/user')
const { SuccessModel, ErrorModel } = require('../model/resModel')
const { getExpires } = require('../utils')
const { set } = require('../db/redis')

module.exports = async (req, res) => {
  
  // 登录
  if (req.method === 'POST' && req.path === '/api/user/login') {
    let { account, password } = req.body
    try {
      let result = await login(account, password)
      if (result[0]) {
        req.session = { account, password }
        set(req.sessionId, req.session)
        return new SuccessModel('登录成功')
      } else {
        return new SuccessModel('账号或密码错误')
      }
    } catch(e) {
      return new ErrorModel('数据库错误')
    }
  }

  // 登录检查
  if (req.method === 'GET' && req.path === '/api/user/check_login') {
    let { account } = req.session
    let resultObj = {}
    if (account) {
      let result = await getVoterStatus(account)
      if (result.length === 2) {
        resultObj.status = result.map(d => d.status)
        return new SuccessModel(Object.assign(resultObj, { account }), '已登录')
      } else if (result.length === 1) {
        resultObj.status = [result[0].status]
        return new SuccessModel(Object.assign(resultObj, { account }), '已登录')
      } else {
        resultObj.status = []
        return new SuccessModel(Object.assign(resultObj, { account }), '已登录')
      }
    } else {
      return new SuccessModel('尚未登录')
    }
  }

  // 退出
  if (req.method === 'GET' && req.path === '/api/user/logout') {
    try {
      res.setHeader('Set-Cookie', `userId=${Date.now()}_${parseFloat(Math.random() * 10)}; path=/; expires=${getExpires()}; httpOnly`)
      return new SuccessModel('已退出')
    } catch (e) {
      return new ErrorModel('退出失败')
    }
  }
}
